/* eslint-disable no-param-reassign */
/* eslint-disable no-bitwise */
/* eslint-disable camelcase */
/* eslint-disable prefer-const */
/**
 * 公共转换js
 */
// 文件转base64
const FiletoBase64 = (file) =>
 new Promise((resolve) => {
  const reader = new FileReader()
  reader.onload = () => {
   const base64 = reader.result || ''
   resolve(base64)
  }
  reader.readAsDataURL(file)
 })
// base64转blob
const Base64toBlob = (base64) => {
 // 去掉url的头，并转换为byte
 const bytes = window.atob(base64.split(',')[1])
 // 处理异常,将ascii码小于0的转换为大于0
 const buffer = new ArrayBuffer(bytes.length)
 const ua = new Uint8Array(buffer)
 for (let i = 0; i < bytes.length; i += 1) {
  ua[i] = bytes.charCodeAt(i)
 }
 return new Blob([buffer], {
  type: 'image/png'
 })
}

// blob/文件转blobUrl
const BlobtoUrl = (blob) => window.URL.createObjectURL(blob)

// 统一转--文件转blobUrl
const FiletoBlobUrl = (file) => FiletoBase64(file).then((res) => BlobtoUrl(Base64toBlob(res)))

// 图片Url路径转base64
const ImageUrltoBase64 = (img) =>
 new Promise((resolve) => {
  const image = new Image()
  image.crossOrigin = ''
  image.src = img
  image.onload = () => {
   const canvas = document.createElement('canvas')
   canvas.width = image.width
   canvas.height = image.height

   const ctx = canvas.getContext('2d')
   if (ctx) {
    ctx.drawImage(image, 0, 0, image.width, image.height)
    const ext = image.src.substring(image.src.lastIndexOf('.') + 1).toLowerCase()
    const dataURL = canvas.toDataURL(`image/${ext}`)
    resolve(dataURL)
   }
  }
 })

// 时分秒换算秒数
const timeToSeconds = (time) => {
 let s = 0
 const hour = time.split(':')[0]
 const min = time.split(':')[1]
 const sec = time.split(':')[2]
 s = Number(hour * 3600) + Number(min * 60) + Number(sec)
 return s
}

// 格式化为指定日期格式
const dateFormat = (date, fmt) => {
 if (!date) {
  return date
 }
 const o = {
  'M+': date.getMonth() + 1, // 月份
  'd+': date.getDate(), // 日
  'h+': date.getHours() % 12 === 0 ? 12 : date.getHours() % 12, // 小时
  'H+': date.getHours(), // 小时
  'm+': date.getMinutes(), // 分
  's+': date.getSeconds(), // 秒
  'q+': Math.floor((date.getMonth() + 3) / 3), // 季度
  'S': date.getMilliseconds() // 毫秒
 }
 const week = {
  0: '/u65e5',
  1: '/u4e00',
  2: '/u4e8c',
  3: '/u4e09',
  4: '/u56db',
  5: '/u4e94',
  6: '/u516d'
 }
 let format = fmt
 if (/(y+)/.test(fmt)) {
  format = format.replace(RegExp.$1, (date.getFullYear().toString()).substr(4 - RegExp.$1.length))
 }
 if (/(E+)/.test(fmt)) {
  format = format.replace(RegExp.$1, ((RegExp.$1.length > 1) ? (RegExp.$1.length > 2 ? '/u661f/u671f' : '/u5468') : '') + (week)[date.getDay().toString()])
 }
 for (let k in o) {
  if (new RegExp(`(${k})`).test(format)) {
   let num = (o)[k]
   format = format.replace(RegExp.$1, RegExp.$1.length === 1 ? num : ('00' + num).substr(('' + num).length))
  }
 }
 return format
}

/**
 * 转化为日期
 */
const toDate = (value)=> {
 if (!value) return new Date()
 const type = typeof value
 if (type === 'string') {
  const time = value
  if (time.split('-').length > 1) {
   return new Date(Date.parse(time.replace(/-/g, '/')))
  }
  if (time.split('/').length > 1) {
   return new Date(Date.parse(time))
  }
  if (time.length >= 8) {
   const timeStr = time.slice(0, 4) + '/' + time.slice(4, 6) + '/' + time.slice(6)
   return new Date(Date.parse(timeStr))
  }
 }
 return new Date(value)
}

/**
 * 接受文本，往里面插入想要的文本
 * @param {*} data 进行转换的文本
 * @param {*} num 隔多少位数插入
 * @param {*} str 插入的参数
 */
const stringAdd = (data, num, str) => {
 const dataString = data.toString()
 const remainder = dataString.length / num
 let ret = dataString.substr(0, num)
 for (let i = 0; i < remainder; i += 1) {
  if (i + 1 < remainder) {
   ret += str + dataString.substr((i + 1) * num, num)
  }
 }
 return ret
}

// 将字符串转换为md5密文
export const MD5 = (value) => {
 let hexcase = 0
 let chrsz = 8

 function safe_add(x, y) {
  let lsw = (x & 0xFFFF) + (y & 0xFFFF)
  let msw = (x >> 16) + (y >> 16) + (lsw >> 16)
  return (msw << 16) | (lsw & 0xFFFF)
 }

 function bit_rol(num, cnt) {
  return (num << cnt) | (num >>> (32 - cnt))
 }

 function md5_cmn(q, a, b, x, s, t) {
  return safe_add(bit_rol(safe_add(safe_add(a, q), safe_add(x, t)), s), b)
 }

 function md5_ff(a, b, c, d, x, s, t) {
  return md5_cmn((b & c) | ((~b) & d), a, b, x, s, t)
 }

 function md5_gg(a, b, c, d, x, s, t ) {
  return md5_cmn((b & d) | (c & (~d)), a, b, x, s, t)
 }

 function md5_hh(a, b, c, d , x , s , t ) {
  return md5_cmn(b ^ c ^ d, a, b, x, s, t)
 }

 function md5_ii(a , b , c , d , x , s , t ) {
  return md5_cmn(c ^ (b | (~d)), a, b, x, s, t)
 }

 function core_md5(x , len ) {
  x[len >> 5] |= 0x80 << ((len) % 32)
  x[(((len + 64) >>> 9) << 4) + 14] = len
  let a = 1732584193
  let b = -271733879
  let c = -1732584194
  let d = 271733878
  for (let i = 0; i < x.length; i += 16) {
   let olda = a
   let oldb = b
   let oldc = c
   let oldd = d
   a = md5_ff(a, b, c, d, x[i + 0], 7, -680876936)
   d = md5_ff(d, a, b, c, x[i + 1], 12, -389564586)
   c = md5_ff(c, d, a, b, x[i + 2], 17, 606105819)
   b = md5_ff(b, c, d, a, x[i + 3], 22, -1044525330)
   a = md5_ff(a, b, c, d, x[i + 4], 7, -176418897)
   d = md5_ff(d, a, b, c, x[i + 5], 12, 1200080426)
   c = md5_ff(c, d, a, b, x[i + 6], 17, -1473231341)
   b = md5_ff(b, c, d, a, x[i + 7], 22, -45705983)
   a = md5_ff(a, b, c, d, x[i + 8], 7, 1770035416)
   d = md5_ff(d, a, b, c, x[i + 9], 12, -1958414417)
   c = md5_ff(c, d, a, b, x[i + 10], 17, -42063)
   b = md5_ff(b, c, d, a, x[i + 11], 22, -1990404162)
   a = md5_ff(a, b, c, d, x[i + 12], 7, 1804603682)
   d = md5_ff(d, a, b, c, x[i + 13], 12, -40341101)
   c = md5_ff(c, d, a, b, x[i + 14], 17, -1502002290)
   b = md5_ff(b, c, d, a, x[i + 15], 22, 1236535329)
   a = md5_gg(a, b, c, d, x[i + 1], 5, -165796510)
   d = md5_gg(d, a, b, c, x[i + 6], 9, -1069501632)
   c = md5_gg(c, d, a, b, x[i + 11], 14, 643717713)
   b = md5_gg(b, c, d, a, x[i + 0], 20, -373897302)
   a = md5_gg(a, b, c, d, x[i + 5], 5, -701558691)
   d = md5_gg(d, a, b, c, x[i + 10], 9, 38016083)
   c = md5_gg(c, d, a, b, x[i + 15], 14, -660478335)
   b = md5_gg(b, c, d, a, x[i + 4], 20, -405537848)
   a = md5_gg(a, b, c, d, x[i + 9], 5, 568446438)
   d = md5_gg(d, a, b, c, x[i + 14], 9, -1019803690)
   c = md5_gg(c, d, a, b, x[i + 3], 14, -187363961)
   b = md5_gg(b, c, d, a, x[i + 8], 20, 1163531501)
   a = md5_gg(a, b, c, d, x[i + 13], 5, -1444681467)
   d = md5_gg(d, a, b, c, x[i + 2], 9, -51403784)
   c = md5_gg(c, d, a, b, x[i + 7], 14, 1735328473)
   b = md5_gg(b, c, d, a, x[i + 12], 20, -1926607734)
   a = md5_hh(a, b, c, d, x[i + 5], 4, -378558)
   d = md5_hh(d, a, b, c, x[i + 8], 11, -2022574463)
   c = md5_hh(c, d, a, b, x[i + 11], 16, 1839030562)
   b = md5_hh(b, c, d, a, x[i + 14], 23, -35309556)
   a = md5_hh(a, b, c, d, x[i + 1], 4, -1530992060)
   d = md5_hh(d, a, b, c, x[i + 4], 11, 1272893353)
   c = md5_hh(c, d, a, b, x[i + 7], 16, -155497632)
   b = md5_hh(b, c, d, a, x[i + 10], 23, -1094730640)
   a = md5_hh(a, b, c, d, x[i + 13], 4, 681279174)
   d = md5_hh(d, a, b, c, x[i + 0], 11, -358537222)
   c = md5_hh(c, d, a, b, x[i + 3], 16, -722521979)
   b = md5_hh(b, c, d, a, x[i + 6], 23, 76029189)
   a = md5_hh(a, b, c, d, x[i + 9], 4, -640364487)
   d = md5_hh(d, a, b, c, x[i + 12], 11, -421815835)
   c = md5_hh(c, d, a, b, x[i + 15], 16, 530742520)
   b = md5_hh(b, c, d, a, x[i + 2], 23, -995338651)
   a = md5_ii(a, b, c, d, x[i + 0], 6, -198630844)
   d = md5_ii(d, a, b, c, x[i + 7], 10, 1126891415)
   c = md5_ii(c, d, a, b, x[i + 14], 15, -1416354905)
   b = md5_ii(b, c, d, a, x[i + 5], 21, -57434055)
   a = md5_ii(a, b, c, d, x[i + 12], 6, 1700485571)
   d = md5_ii(d, a, b, c, x[i + 3], 10, -1894986606)
   c = md5_ii(c, d, a, b, x[i + 10], 15, -1051523)
   b = md5_ii(b, c, d, a, x[i + 1], 21, -2054922799)
   a = md5_ii(a, b, c, d, x[i + 8], 6, 1873313359)
   d = md5_ii(d, a, b, c, x[i + 15], 10, -30611744)
   c = md5_ii(c, d, a, b, x[i + 6], 15, -1560198380)
   b = md5_ii(b, c, d, a, x[i + 13], 21, 1309151649)
   a = md5_ii(a, b, c, d, x[i + 4], 6, -145523070)
   d = md5_ii(d, a, b, c, x[i + 11], 10, -1120210379)
   c = md5_ii(c, d, a, b, x[i + 2], 15, 718787259)
   b = md5_ii(b, c, d, a, x[i + 9], 21, -343485551)
   a = safe_add(a, olda)
   b = safe_add(b, oldb)
   c = safe_add(c, oldc)
   d = safe_add(d, oldd)
  }
  return [a, b, c, d]
 }

 function str2binl(str  = []) {
  let bin = []
  let mask = (1 << chrsz) - 1
  for (let i = 0; i < str.length * chrsz; i += chrsz) {
   bin[i >> 5] |= (str.charCodeAt(i / chrsz) & mask) << (i % 32)
  }
  return bin
 }

 function binl2hex(binarray) {
  let hex_tab = hexcase ? '0123456789ABCDEF' : '0123456789abcdef'
  let str = ''
  for (let i = 0; i < binarray.length * 4; i += 1) {
   str += hex_tab.charAt((binarray[i >> 2] >> ((i % 4) * 8 + 4)) & 0xF) + hex_tab.charAt((binarray[i >> 2] >> ((i % 4) * 8)) & 0xF)
  }
  return str
 }
 return binl2hex(core_md5(str2binl(value), value.length * chrsz))
}

/**
 * @param {*} formArr 表单内容
 * @param {*} data 接口的对象数据
 */
const formFun = (formArr, data) => {
 let result = []
 const ret = formArr
 if (!data) {
  result = ret
  return result
 }

 for (let i = 0; i < formArr.length; i += 1) {
  const d = {
   ...formArr[i]
  }
  if (formArr[i].time) {
   d.value = dateFormat(data[formArr[i].key], 'HH:mm:ss')
  } else if (formArr[i].obj) {
   d.value = formArr[i].obj[data[formArr[i].key]]
  } else {
   d.value = data[formArr[i].key] || data[formArr[i].defaultKey]
  }
  result.push(d)
 }
 return result
}

export class PostbirdMp4ToBlob {
  constructor(selector , assetUrl, mimeCodec){
    this.mediaSource = new MediaSource()
    this.mimeCodec = 'video/mp4; codecs="avc1.640028, mp4a.40.2"'
    this.video = selector
    this.assetUrl = assetUrl
    this.checkSupported()
  }

 // 初始化 selector / assetUrl / mimeCodec / autoPlay
 // selector：video的选择器 exp: '#video'
 // assetUrl: video的请求地址 exp : './v.mp4'
 // mimeCodec: 编码模式 exp: 'video/mp4; codecs="avc1.640028, mp4a.40.2"'
 // 检查是否支持 MediaSource 或者 mimeCodec
 checkSupported() {
  if ('MediaSource' in window && MediaSource.isTypeSupported(this.mimeCodec)) {

  } else {
   this.video.src = this.assetUrl // 如果不支持，则直接将 src 修改成原始的url，保证兼容性
   console.error('Unsupported MediaSource or unsupported MIME type or codec:', this.mimeCodec)
  }
 }
 // 开启
 start() {
  console.log(this.mediaSource.readyState)
  this.video.src = URL.createObjectURL(this.mediaSource)
  console.log(this.video.src)
  this.mediaSource.addEventListener('sourceopen', this.sourceOpen)
 }
 // MediaSource sourceopen 事件处理
 sourceOpen() {
  console.log(this.mediaSource.readyState)
  let sourceBuffer = this.mediaSource.addSourceBuffer(this.mimeCodec)
  this.fetch(this.assetUrl).then((buf ) => {
   sourceBuffer.addEventListener('updateend', () => {
    this.mediaSource.endOfStream()
    console.log(this.mediaSource.readyState)
   })
   sourceBuffer.appendBuffer(buf)
  })
 }
 // 基于 XHR 的简单封装
 // arguments - url 视频链接地址
 fetch(url) {
  return new Promise((resolve, reject) => {
   let xhr = new XMLHttpRequest()
   xhr.open('get', url)
   xhr.responseType = 'arraybuffer'
   xhr.onload = () => {
    resolve(xhr.response)
   }
   xhr.send()
  })
 }
}

export default {
 FiletoBase64,
 Base64toBlob,
 BlobtoUrl,
 FiletoBlobUrl,
 ImageUrltoBase64,
 dateFormat,
 toDate,
 timeToSeconds,
 stringAdd,
 MD5,
 formFun,
 PostbirdMp4ToBlob
}
